## -*- coding: utf-8 -*-
from apigate import apigate
from flask import request, render_template
import requests, json
from contextlib import closing
from flask import g
import time
from runserver import app
import sqlite3

headers = {'Content-Type': 'application/json'}
DATABASE = 'api.db'

edge={'cn':'http://127.0.0.1/submit','us':'http://127.0.0.1/submit'}

def connect_db():
    return sqlite3.connect(DATABASE)

@apigate.before_request
def before_request():
    g.db = connect_db()

@apigate.teardown_request
def teardown_request(exception):
    if hasattr(g, 'db'):
        g.db.close()

def init_db():
    with closing(connect_db()) as db:
        with app.open_resource('../db/init.sql') as f:
            db.cursor().executescript(f.read().decode('utf-8'))
        db.commit()
def query_db(query, args=(), one=False):
    cur = g.db.execute(query, args)
    rv = [dict((cur.description[idx][0], value)
               for idx, value in enumerate(row)) for row in cur.fetchall()]
    return (rv[0] if rv else None) if one else rv




@apigate.route('/')
def hello_world():
   return 'api-gateway添加用户接口'

@apigate.route('/submit', methods=['POST'])
def Add_apigate():
    user=request.form['user']
    zone=request.form['zone']
    print(user)
    response = requests.post(edge[zone], data=json.dumps({'user':user,'zone':zone}), headers=headers)
    if response.json()['msg'] == 'api开通成功':
        sql = 'insert into api_user(user,zone,created,clientId,clientSecret) values(?,?,?,?,?) '
        clientId = response.json()['spec']['clientId']
        clientSecret = response.json()['spec']['clientSecret']
        cur = g.db.execute(sql, (user, zone, time.strftime("%Y-%m-%d %H:%M", time.localtime()),clientId,clientSecret))
        g.db.commit()
    else:
        print('写入数据库失败')
    return response.text

@apigate.route('/user_list')
def User_list():
    for user in query_db('select * from api_user'):
        print(user)
        username=user['user']
        created_time=user['created']
    user = query_db('select * from api_user')
    return render_template('apigate.html',result=user)